package com.zndroid.logcat.core;

import android.os.Parcel;
import android.os.Parcelable;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lzy on 2021/1/15.
 */
public final class LogInfo implements Parcelable {
    private static final Pattern PATTERN = Pattern.compile(
            "([0-9^-]+-[0-9^ ]+ [0-9^:]+:[0-9^:]+\\.[0-9]+) +([0-9]+) +([0-9]+) ([VDIWEF]) ([^ ]*) *: (.*)");

    static final ArrayList<String> IGNORED_LOG = new ArrayList<String>() {{
        add("--------- beginning of crash");
        add("--------- beginning of main");
        add("--------- beginning of system");
    }};

    private String time;
    private String processId;
    private String threadId;
    private String priority;
    private String tag;
    private String content;
    private String origin;

    protected LogInfo(Parcel in) {
        this.time = in.readString();
        this.processId = in.readString();
        this.threadId = in.readString();
        this.priority = in.readString();
        this.tag = in.readString();
        this.content = in.readString();
        this.origin = in.readString();
    }

    protected LogInfo() {
    }

    public static LogInfo create(String line) {
        Matcher matcher = PATTERN.matcher(line);
        // 判断日志格式是否合法（目前发现华为手机有在日志的 TAG 中加空格导致识别不出来，这种无法做兼容）
        if (!matcher.find()) {
            return null;
        }

        LogInfo info = new LogInfo();
        info.time = matcher.group(1);
        info.processId = matcher.group(2);
        info.threadId = matcher.group(3);
        info.priority = matcher.group(4);
        info.tag = matcher.group(5);
        info.content = matcher.group(6);
        info.origin = line;
        return info;
    }

    public static final Creator<LogInfo> CREATOR = new Creator<LogInfo>() {
        @Override
        public LogInfo createFromParcel(Parcel in) {
            return new LogInfo(in);
        }

        @Override
        public LogInfo[] newArray(int size) {
            return new LogInfo[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.time);
        dest.writeString(this.processId);
        dest.writeString(this.threadId);
        dest.writeString(this.priority);
        dest.writeString(this.tag);
        dest.writeString(this.content);
        dest.writeString(this.origin);
    }

    public String getTime() {
        return time;
    }

    public String getProcessId() {
        return processId;
    }

    public String getThreadId() {
        return threadId;
    }

    public String getPriority() {
        return priority;
    }

    public String getTag() {
        return tag;
    }

    public String getContent() {
        return content;
    }

    public String getOrigin() {
        return origin;
    }
}
